package mirrormonkey.rpc.module;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;

import mirrormonkey.util.IdGenerator;

public class CallRegistry {

	public static final int NO_RESPONSE_EXPECTED = -1;

	protected final IdGenerator idGen;

	protected final Map<Integer, RegisteredCall> currentCalls;

	protected final Collection<Integer> toRemove;

	public CallRegistry() {
		idGen = new IdGenerator();
		idGen.reserve(NO_RESPONSE_EXPECTED);
		currentCalls = new LinkedHashMap<Integer, RegisteredCall>();
		toRemove = new LinkedList<Integer>();
	}

	public synchronized int registerCall(RegisteredCall call) {
		int id = idGen.generateAndReserve();
		currentCalls.put(Integer.valueOf(id), call);
		return id;
	}

	public synchronized RegisteredCall getRegisteredCall(int callId) {
		return currentCalls.get(Integer.valueOf(callId));
	}

	public synchronized void update(float tpf) {
		for (RegisteredCall i : currentCalls.values()) {
			i.update(tpf);
		}

		for (Integer i : toRemove) {
			idGen.release(i);
			currentCalls.remove(i);
		}
		toRemove.clear();
	}

	public void removeCall(RegisteredCall registeredCall) {
		toRemove.add(Integer.valueOf(registeredCall.id));
	}

}
